/* 
 *   Date       Developer   Description
 *   
 *
 *   Classname:  com.SystemInterface.Common.services.JSProcessor
 * 
 *   Date:   2014-3-17
 * 
 *   The source code contained in this listing is proprietary to
 *   HLJ POST YITONG INFO-NET CO.,LTD.
 * 
 *   Unauthorized copying, adaptation, distribution, use, or display
 *   is strictly prohibited.
 *   This software is Copyright 2014 HLJ POST YITONG INFO-NET CO.,LTD.
 */
package com.titan.demo.camel.utils.processor;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;


/**
 *
 *
 * @author Administrator
 *
 */
public class JSProcessor implements Processor {
    private String script;
    
    
    @Override
    public void process(Exchange exchange) throws Exception {
        Message in = exchange.getIn();
        Message out = exchange.getOut();
        
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        Compilable compilable = (Compilable)engine;
        
        Bindings bindings = engine.createBindings();
        bindings.put("body", in.getBody());

        CompiledScript compiled = compilable.compile(script);
        compiled.eval(bindings);
        
        out.setBody(bindings.get("body"));
        out.setHeaders(in.getHeaders());
    }
    
    
    public String getScript() {
        return script;
    }
    
    public void setScript(String script) {
        this.script = script;
    }
}

